<!-- 合同模板列表 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew :title="title" :showBack="true"></PageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20" :margin-top="20">
      <template #left>
        <a-input-search
          :style="{ width: '220px' }"
          placeholder="模板名称"
          search-button
          @search="onSearch"
          @press-enter="onSearch"
          v-model="nameSearch"
        />
      </template>
      <template #right>
        <a-button type="primary" @click="add(null)">新增模板</a-button>
        <a-button type="outline" @click="del(null)" status="danger"
          >批量删除</a-button
        >
      </template>
    </ConditionBox>
    <TableTurn :tableData="getTableData" ref="tableRef" :args="args">
      <a-table-column :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="name" title="合同模板名称">
      </a-table-column>
      <a-table-column :width="200" title="合同类型">
        <template #cell>
          {{ typeName }}
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="remark" title="描述">
      </a-table-column>
      <a-table-column
        align="center"
        :width="150"
        title="启用状态"
        dataIndex="enable"
      >
        <template #cell="{ record }">
          <a-tag
            class="enable"
            :color="
              record.enable === 1
                ? `rgb(var(--green-1))`
                : 'rgb(var(--danger-1))'
            "
            :style="{
              color:
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))',
              '--enable':
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))'
            }"
          >
            {{ record.enable === 1 ? '启用' : '停用' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="default" title="设为默认">
        <template #cell="{ record }">
          <a-switch
            :checked-value="1"
            :un-checked-value="2"
            v-model="record.default"
            @change="changeDefault(record)"
          />
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="" title="操作" fixed="right">
        <template #cell="{ record }">
          <a-tooltip content="预览">
            <icon-eye
              size="20"
              @click="goPreview(record)"
              style="
                padding-bottom: 3px;
                padding-right: 10px;
                color: #5085ff;
                cursor: pointer;
              "
            />
          </a-tooltip>
          <a-tooltip content="复制">
            <icon-copy
              size="18"
              style="
                padding-bottom: 3px;
                padding-right: 10px;
                color: #5085ff;
                cursor: pointer;
              "
              @click="goCopy(record)"
            />
          </a-tooltip>
          <a-tooltip content="编辑">
            <IconFont
              type="icon-edit"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
              @click="goEdit(record)"
            />
          </a-tooltip>
          <a-tooltip content="删除" position="left">
            <a-popconfirm content="是否确认删除该条数据?" @ok="del(record)">
              <IconFont
                type="icon-delete"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer'
                }"
              />
            </a-popconfirm>
          </a-tooltip>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <AddTemplate
    v-model:visible="templateVisible"
    :data="currRecord.data"
    @save="refresh"
  />
  <CopyModal
    v-model:visible="copyVisible"
    @copy-emit="copyEmit"
    @copyEditEmit="copyEditEmit"
    :validateFun="validateName"
    :data="currRecord.data"
  />
</template>

<script lang="tsx" setup>
import {
  GetContractTemplateList,
  AddContractTemplate,
  GetContractTemplateDefault,
  CheckContractTemplate,
  DelContractTemplate
} from '@/apis/management/contract/baseSetting';
import AddTemplate from '../AddTemplate/index.vue';
import { cloneDeep } from 'lodash';
import { Message, Modal } from '@arco-design/web-vue';
import { validateRules } from '@/utils/common';

const router = useRouter();
const route = useRoute();
let typeId = +route.query.typeId;

const typeName = route.query.name;
const title = `${typeName}合同模板`;
let templateRef = ref();

// 表格配置
const args = {
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
};

// 储存当前数据
const currRecord: any = reactive({
  data: {}
});
let tableRef = ref();
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);
let nameSearch = ref(''); // 搜索框值

// 获取表格数据
const getTableData = async (pageData?: any) => {
  try {
    const res = await GetContractTemplateList({
      ...pageData,
      typeId
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

const templateData = reactive({
  data: {
    isCopyEdit: false, // 是否为复制编辑
    baseInfoData: {
      name: '',
      enable: 1,
      remark: ''
    },
    designData: {
      text: '',
      codes: []
    },
    pageHeaderSettingData: {
      style: 1,
      enterpriseName: '',
      logo: ''
    },
    fileSettingData: {}
  }
});
let templateVisible = ref(false);
// 新增
const add = (record?: any) => {
  currRecord.data = cloneDeep(templateData);
  templateVisible.value = true;
};

const goEdit = (record: any, formData?: any) => {
  currRecord.data = cloneDeep(record);
  if (formData) {
    currRecord.data.isCopyEdit = true;
    delete currRecord.data.id;
    delete currRecord.data.deletedAt;
    delete currRecord.data.createdAt;
    delete currRecord.data.updatedAt;
  }
  console.log('====================================123123');
  console.log(currRecord.data);
  console.log(formData);
  console.log('====================================');
  templateVisible.value = true;
};

// 搜索框搜索事件
const onSearch = () => {
  refresh();
};

const changeDefault = async ({
  typeId,
  id
}: {
  typeId: number;
  id: number;
}) => {
  try {
    await GetContractTemplateDefault({
      id,
      typeId
    });
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 预览
const goPreview = (record: any) => {
  Modal.open({
    title: '模板预览',
    hideCancel: true,
    bodyStyle: {
      maxHeight: '600px',
      overflow: 'auto'
    },
    width: '80%',
    content: (
      <>
        <div v-html={record.text}></div>
      </>
    )
  });
};

let copyVisible = ref(false);
let currId = ref();
// 显示复制弹窗
const goCopy = (record: any) => {
  currRecord.data = record;
  currId.value = record.id;
  copyVisible.value = true;
};
const copyEmit = async (formData: any) => {
  try {
    const temp = cloneDeep(formData);
    delete temp.id;
    delete temp.deletedAt;
    delete temp.createdAt;
    delete temp.updatedAt;
    temp.default = 0;
    // let copyName = `copy-${temp.name}`;
    // let i = 1;
    // while (await nameAlreadyExists(copyName, temp.typeId)) {
    //   copyName = `copy-${copyName}-${i}`;
    //   i++;
    // }
    // temp.name = copyName;
    await AddContractTemplate(temp);
    console.log(temp);

    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 复制弹窗点击确认并编辑
const copyEditEmit = (formData: any) => {
  goEdit(formData, 'copy');
};

// 模板查重函数
const validateName = async (name: string) => {
  try {
    if (name === currRecord.data.name && currRecord.data.id) {
      //
    } else {
      const data = {
        id: currRecord.data.typeId,
        name
      };
      const res = await validateRules(CheckContractTemplate, data);
      return Promise.resolve(res);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const nameAlreadyExists = async (name: string, id: number) => {
  // 在此处编写检查名称是否已存在的逻辑
  try {
    const res = await CheckContractTemplate({
      name,
      id
    });
    if (res.code === 400) return true;
    return false;
  } catch (error: unknown) {
    console.log(error);
  }
};

const del = async (record: any) => {
  try {
    if (!record) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              if (
                selectedListData.value.find((item: any) => item.default === 1)
              ) {
                Message.error('默认模板不能删除！');
              } else {
                await DelContractTemplate({
                  ids: selectedList.value
                });
                tableRef.value.selectedList = [];
                refresh();
              }
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      if (record.default === 1) Message.error('默认模板不能删除！');
      else {
        await DelContractTemplate({
          ids: [record.id]
        });
        tableRef.value.selectedList = [];
        refresh();
      }
    }
    // await DelContractTemplate({
    //   id
    // });
    // refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 刷新表格数据
const refresh = () => {
  tableRef.value.loadData();
};
</script>

<style scoped lang="less">
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
</style>
